package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServleRequest {
    private Socket socket;
    private String method;//请求方式
    private String uri;//抽象路径
    private String protocol;//协议版本
    //消息头相关信息
    Map<String, String> headers = new HashMap<>();

    public HttpServleRequest(Socket socket) throws IOException {
        this.socket = socket;
        //1.解析请求行
        parseRequestLine();
        //2.解析消息头
        parseHeaders();
        //3.解析消息正文
        parseContent();


    }//1.解析请求行
    private void parseRequestLine() throws IOException {
        String line = reandLine();
        System.out.println("请求行:" + line);
        //请求行相关信息

        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];
        System.out.println("method:" + method);
        System.out.println("uri:" + uri);
        System.out.println("protocol:" + protocol);
    }//2.解析消息头
    private void parseHeaders() throws IOException {
        while (true) {
           String line = reandLine();
            if (line.isEmpty()) {//如果读取的是空字符串说明单独读取了CRLF
                break;
            }
            System.out.println("消息头:" + line);
            String[]data = line.split(":\\s");
            headers.put(data[0], data[1]);
        }
        System.out.println("headers:" + headers);
    }//3.解析消息正文
    private void parseContent(){}

    private String reandLine() throws IOException {
        //抛出异常
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char cur = 'a';//保存本次读取到的字符
        char pre = 'a';//保存上次读取到的字符
        int d;
        while ((d = in.read()) != -1) {
            cur = (char) d;//本次读取到的字符
            if (pre == 13 && cur == 10) {//判断是否连续读取到了回车+换行
                break;
            }     //添加元素字符串
            builder.append(cur);
            pre = cur;//下次循环前将本次读取到的字符记为上次读取的字符
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name) {
        return headers.get(name);
    }
}
